import { history } from 'umi';
import { clearLoginAfter } from '@/events/rxEvent';
import Cookies from 'js-cookie';
import storejs from 'storejs';
import api from '@/network/api';

const {
  userApi: { getUserinfo, clearLogin },
} = api;

let initState = () => ({
  //权限
  authority: ['login'],

  // 用户信息
  user: {
    userId: '111',
    name: '',
    orgId: '',
    orgList: '',
    telNum: '',
    empNum: '',
    username: '',
  },

});


export default {
  namespace: 'user',
  state: { ...initState() },
  effects: {
    // 获取用户信息
    *getUserinfo({ payload }, { call, put }) {
      var obj = { params: {}, body: payload };
      const rs = yield call(getUserinfo, obj);
      if (rs.success) {
        var data = rs.data;
        storejs('userId', rs.data.id);
        Cookies.set('userId', rs.data.id);
        let authority = ['login'];
        if(rs.data.authorities) authority.push(...rs.data.authorities)
        yield put({
          type: 'user/setState',
          payload: {
            user: {
              ...data,
              userId: data.id,
              name: data.username,
              username: data.username,
            },
            authority: authority,
          },
        });
      }
      return Promise.resolve(rs);
    },

    // 退出登录
    *clearLogin({ payload }, { call, put, select }) {
      const { userId } = yield select(state => state.user.user);
      if (userId) clearLogin({ params: {}, body: { userId: userId } });
      yield put({ type: 'initAll', payload: {} });
      storejs.remove('token');
      storejs.remove('userId');
      Cookies.remove('userId');
      clearLoginAfter.next();
      history.replace('/user/login');
    },

    // models 初始化
    *initAll({ payload }, { call, put }) {
      yield put({ type: 'init' });
      yield put({ type: 'masterGlobal/init' });
    },
  },

  reducers: {
    setState(state, action) {
      return { ...state, ...action.payload };
    },
    init(state, action) {
      return { ...initState(), ...action.payload };
    },
  },
};